package datastructure.unionfind;

public class UnionFind1 implements UF {

    private int[] id;

    public UnionFind1(int size) {
        id = new int[size];
        for (int i = 0; i < size; i++) {
            id[i] = i;
        }
    }

    @Override
    public int getSize() {

        return id.length;
    }

    // 查看元素p对饮的集合编号
    private int find(int p) {
        if (p < 0 || p >= id.length)
            throw new IllegalArgumentException("p is out of bound.");
        return id[p];
    }

    @Override
    public boolean isConnected(int p, int q) {
        // 复杂度分析 查找 logn
        int findP = find(p);
        int findQ = find(q);
        return findP == findQ;
    }

    @Override
    public void unionElements(int p, int q) {
        int findP = find(p);
        int findQ = find(q);
        for (int i = 0; i < id.length; i++) {
            if (id[i] == findQ) {
                id[i] = findP;
            }
        }
    }

}
